package com.ruoyi.buss.utils;

import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.nio.charset.Charset;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.apache.http.HttpEntity;
import org.apache.http.NameValuePair;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.config.RequestConfig;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.entity.ContentType;
import org.apache.http.entity.StringEntity;
import org.apache.http.entity.mime.MultipartEntityBuilder;
import org.apache.http.entity.mime.content.FileBody;
import org.apache.http.entity.mime.content.StringBody;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.message.BasicNameValuePair;
import org.apache.http.util.EntityUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.web.multipart.MultipartFile;

import com.alibaba.fastjson.JSON;

public class HttpClientHelper {
    private static Logger logger = LoggerFactory.getLogger(HttpClientHelper.class);

    private HttpClientHelper() {

    }

    /**
     * 发起POST请求
     *
     * @param url   url
     * @param paramMap 参数的Map格式
     */
    public static String sendPost(String url, Map<String, String> paramMap) {
        logger.info("开始发起POST请求，请求地址为{}，参数为{}", url, JSON.toJSON(paramMap));
        CloseableHttpResponse response = null;
        String responseEntityStr = "";
        try (CloseableHttpClient httpClient = HttpClients.createDefault()) {
            String encoding = "utf-8";
            //创建post请求对象
            HttpPost httpPost = new HttpPost(url);
            //装填请求参数
            List<NameValuePair> list = new ArrayList<>();
            for (Map.Entry<String, String> entry : paramMap.entrySet()) {
                list.add(new BasicNameValuePair(entry.getKey(), entry.getValue()));
            }
            //设置参数到请求对象中
//            httpPost.setEntity(new UrlEncodedFormEntity(list, encoding));
            httpPost.setEntity(new StringEntity(JSON.toJSON(paramMap).toString(), Charset.forName("UTF-8")));
//            httpPost.setHeader("Content-type", "application/x-www-form-urlencoded");
            httpPost.setHeader("Content-Type","application/json");
            httpPost.setHeader("User-Agent", "Mozilla/4.0 (compatible; MSIE 5.0; Windows NT; DigExt)");
            response = httpClient.execute(httpPost);
            try {
                System.out.println(response.getStatusLine());
                HttpEntity resEntity = response.getEntity();
                if (resEntity != null) {
                    responseEntityStr = EntityUtils.toString(response.getEntity());
                    System.out.println(responseEntityStr);
                    System.out.println("Response content length: " + resEntity.getContentLength());
                    return responseEntityStr;
                }
                EntityUtils.consume(resEntity);
            } finally {
                response.close();
            }
        } catch (IOException e) {
            logger.error("POST请求发出失败，请求的地址为{}，参数为{}，错误信息为{}", url, JSON.toJSON(paramMap), e.getMessage(), e);
        } finally {
            try {
                if (response != null) {
                    response.close();
                }
            } catch (IOException e) {
                logger.error("POST请求response关闭异常，错误信息为{}", e.getMessage(), e);
            }
        }

        return responseEntityStr;
    }

    /**
     * 发起GET请求
     *
     * @param urlParam url请求，包含参数
     */
    public static void sendGet(String urlParam) {
        logger.info("开始发起GET请求，请求地址为{}", urlParam);
        HttpGet httpGet = new HttpGet(urlParam);
        CloseableHttpResponse response = null;
        try (CloseableHttpClient httpClient = HttpClients.createDefault()) {
            response = httpClient.execute(httpGet);
            int status = response.getStatusLine().getStatusCode();
            logger.error("GET请求发出成功，请求的地址为{}，返回状态为{}", urlParam, status);
        } catch (IOException e) {
            logger.error("GET请求发出失败，请求的地址为{}，错误信息为{}", urlParam, e.getMessage(), e);
        } finally {
            try {
                if (response != null) {
                    response.close();
                }
            } catch (IOException e) {
                logger.error("GET请求response关闭异常，错误信息为{}", e.getMessage(), e);
            }
        }
    }

    /**
     * 发起文件上传
     *
     * @param url   url
     * @param file 上传得文件
     */
    public static String uploadFile(String url, MultipartFile file) {
        logger.info("开始发起POST请求，请求地址为{}，参数为{}", url );
        String responseEntityStr = "";
        CloseableHttpClient httpclient = HttpClients.createDefault();
        try {
            HttpPost httppost = new HttpPost(url);

            RequestConfig requestConfig = RequestConfig.custom().setConnectTimeout(200000).setSocketTimeout(200000).build();
            httppost.setConfig(requestConfig);

            FileBody bin = new FileBody(HttpClientHelper.multipartFileToFile(file));
            StringBody comment = new StringBody("This is comment", ContentType.TEXT_PLAIN);

            HttpEntity reqEntity = MultipartEntityBuilder.create().addPart("file", bin).addPart("comment", comment).build();

            httppost.setEntity(reqEntity);

            System.out.println("executing request " + httppost.getRequestLine());
            CloseableHttpResponse response = httpclient.execute(httppost);
            try {
                System.out.println(response.getStatusLine());
                HttpEntity resEntity = response.getEntity();
                if (resEntity != null) {
                    responseEntityStr = EntityUtils.toString(response.getEntity());
                    System.out.println(responseEntityStr);
                    System.out.println("Response content length: " + resEntity.getContentLength());
                    return responseEntityStr;
                }
                EntityUtils.consume(resEntity);
            } finally {
                response.close();
            }
        } catch (ClientProtocolException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        } catch (Exception e){
            e.printStackTrace();
        } finally {
            try {
                httpclient.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
        return responseEntityStr;
    }

    /**
     * MultipartFile 转 File
     *
     * @param file
     * @throws Exception
     */
    public static File multipartFileToFile(MultipartFile file) throws Exception {

        File toFile = null;
        if (file.equals("") || file.getSize() <= 0) {
            file = null;
        } else {
            InputStream ins = null;
            ins = file.getInputStream();
            toFile = new File(file.getOriginalFilename());
            inputStreamToFile(ins, toFile);
            ins.close();
        }
        return toFile;
    }

    //获取流文件
    private static void inputStreamToFile(InputStream ins, File file) {
        try {
            OutputStream os = new FileOutputStream(file);
            int bytesRead = 0;
            byte[] buffer = new byte[8192];
            while ((bytesRead = ins.read(buffer, 0, 8192)) != -1) {
                os.write(buffer, 0, bytesRead);
            }
            os.close();
            ins.close();
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    /**
     * 删除本地临时文件
     * @param file
     */
    public static void delteTempFile(File file) {
        if (file != null) {
            File del = new File(file.toURI());
            del.delete();
        }
    }


    public static void main(String[] args) {
        String url = "https://jiashubing.cn/tencenttest";
        //需要传入的参数
        Map<String, String> map = new HashMap<>();
        map.put("code", "js");
        map.put("day", "0");
        map.put("city", "北京");
        map.put("dfc", "1");
        map.put("charset", "utf-8");
        sendPost(url, map);


        String urlParam = "https://jiashubing.cn/talk/document?fileid=1234ji贾树丙";
        sendGet(urlParam);
    }

}
